#!/bin/bash
echo "===== 开始磁盘性能测试和优化 ====="
# 记录开始时间
start_time=$(date +%s.%N)
# 设置错误处理机制
set -eo pipefail
trap '{
    echo "===== 错误信息 ====="
    echo "错误发生，脚本终止"
}' ERR
# 磁盘I/O性能调优参数
DISK="/dev/sda"  # 根据实际情况修改为具体磁盘设备
IOWAIT_THRESHOLD=5.0
QUEUE_LENGTH=128
READ_TIMEOUT=30
# 收集原始指标
echo "===== 原始性能指标 ====="
iostat -d -k | grep ${DISK}
hdparm -I ${DISK}  # 显示磁盘详细信息和健康状态
# 运行调优命令
if [ "$(cat /proc/sys/vm/laptop_mode)" != "0" ]; then
    echo "1" > /proc/sys/vm/laptop_mode
fi
if [ "$(cat /proc/sys/block/${DISK}/queue/scheduler)" != "deadline" ]; then
    echo deadline > /proc/sys/block/${DISK}/queue/scheduler
fi
echo ${QUEUE_LENGTH} > /proc/sys/block/${DISK}/queue/max_queue_length
if [ "${READ_TIMEOUT}" -ne "$(cat /sys/block/${DISK}/rq/timeout)" ]; then
    echo ${READ_TIMEOUT} > /sys/block/${DISK}/rq/timeout
fi
# 收集调优后的指标
echo "===== 调优后性能指标 ====="
iostat -d -k | grep ${DISK}
hdparm -I ${DISK}
# 检查是否有错误发生
if [ $? -ne 0 ]; then
    echo "磁盘调优过程中出现错误，请检查日志"
    exit 1
fi
# 记录结束时间
end_time=$(date +%s.%N)
duration=$(echo "$end_time - $start_time" | bc)
# 结构化输出性能指标
echo "===== 性能优化结果 ====="
echo '{
    "total_time": "'$duration'",
    "iowait_before": '$(grep ${DISK} /tmp/disk_test.log | awk '{print $3}' before Tune)',
    "iowait_after": '$(grep ${DISK} /tmp/disk_test.log | awk '{print $3}' after Tune)',
    "queue_length_before": '$(grep ${DISK} /tmp/disk_test.log | awk '{print $4}' before Tune)',
    "queue_length_after": '$(grep ${DISK} /tmp/disk_test.log | awk '{print $4}' after Tune)',
    "disk_throughput_before": '$(grep ${DISK} /tmp/disk_test.log | awk '{print $5}' before Tune)KB/s',
    "disk_throughput_after": '$(grep ${DISK} /tmp/disk_test.log | awk '{print $5}' after Tune)KB/s',
    "health_status_before": "'$(hdparm -I ${DISK} 2>&1 | grep Health | awk '{print $7}')'",
    "health_status_after": "'$(hdparm -I ${DISK} 2>&1 | grep Health | awk '{print $7}')'"
}'
exit 0